package com.example.mychat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mychat.dto.MessageWithThumb;
import com.example.mychat.entity.Message;
import com.example.mychat.mapper.LikesMapper;
import com.example.mychat.mapper.MessageMapper;
import com.example.mychat.service.IMessageService;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl implements IMessageService {
    @Resource
    private MessageMapper messageMapper;

    @Resource
    LikesMapper likeMapper;

    @Override
    @Cacheable(value = "messageByTime")
    public List<Message> findByTime() {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("receiverId", -1);
        queryWrapper.gt("expirationTime", new Date());
        queryWrapper.orderByDesc("time");
        return messageMapper.selectList(queryWrapper);
    }

    @Override
    @Cacheable(value = "messageByLikeNum")
    public List<MessageWithThumb> findByLikeNum() {
        return messageMapper.findMessageByLikeNum();
    }

    @Override
    @Cacheable(value = "messageByLikeNum")
    public List<MessageWithThumb> findByLikeNum(String username) {
        String maxBeLikedName = likeMapper.selectMaxBeLikeName(username);
        List<MessageWithThumb> messageList = messageMapper.findMessageByLikeNum();
        if (maxBeLikedName != null) {
            int size = messageList.size();
            int count = 0;
            for (int i = 0; i < size; ++i) {
                if (messageList.get(i).getUsername().equals(maxBeLikedName)) {
                    MessageWithThumb message = messageList.get(i);
                    messageList.remove(i);
                    messageList.add(count, message);
                    ++count;
                    if (count == 2) {
                        break;
                    }
                }
            }
        }
        return messageList;
    }

    @Override
    @Cacheable(value = "message", key = "#receiverId")
    public List<Message> findByReceiverId(int receiverId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("receiverId", receiverId);
        queryWrapper.gt("expirationTime", new Date());
        queryWrapper.orderByDesc("time");
        return messageMapper.selectList(queryWrapper);
    }
}
